package com.deshan.websys.code.entry;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

//@Component
//@ServerEndpoint("/myWs/{userId}")
public class WsEndpoint {
    private static ConcurrentHashMap<String, WsEndpoint> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    //用户id
    private String userId;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
        }
        System.out.println("连接成功");
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
        System.out.println("关闭连接");

    }

    @OnMessage
    public void onMessage(String text, Session session) {
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
    }

    public static void sendInfo(String userId, String message) {
        System.out.println("后端发送前端web数据userId:" + userId + "发送消息：" + message);
        if (webSocketMap.containsKey(userId)) {
            try {
                webSocketMap.get(userId).session.getBasicRemote().sendText("后端发送前端web数据userId" + userId + "，内容：" + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
